"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _Lane = _interopRequireDefault(require("./components/Lane"));

var _List = _interopRequireDefault(require("./components/List"));

var _CreateNode = _interopRequireDefault(require("./components/CreateNode"));

var _ActionButtons = _interopRequireDefault(require("./components/ActionButtons"));

var _antd = require("antd");

var _ahooks = require("ahooks");

var _useHooks = _interopRequireDefault(require("./useHooks"));

var _tools = require("./tools");

var _defaultData = _interopRequireDefault(require("./defaultData"));

var _iconfont = _interopRequireDefault(require("./components/assets/font/iconfont"));

var _tools2 = require("./components/Lane/tools");

require("./style/index");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

window._globalAssets = {};
var ArchDesign = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, api) {
  var {
    assets,
    moduleConfig,
    data,
    onAddLink,
    onRemoveLink,
    onRemoveNode,
    onCreateNode,
    onUpdateNode,
    onUndoOrRedo,
    onAutoSave,
    onSave,
    onChange,
    autoSaveInterval = 0,
    showActions,
    actions,
    appendActions,
    registerList,
    defaultNodeShape,
    defaultEdgeShape = _tools.defaultEdgeShapeName,
    moduleNodeShape = _tools.defaultModuleNodeName,
    drawerRootNode,
    cache
  } = _ref;
  window._saveInterval = autoSaveInterval;
  window._useCache = cache;
  var archWrapper = (0, _react.useRef)(null);
  var [createModalKey, setCreateModalKey] = (0, _react.useState)((0, _tools.getKey)());
  var [laneKey, setLaneKey] = (0, _react.useState)((0, _tools.getKey)());
  var [graph, setGraph] = (0, _react.useState)();
  var [visible, setVisible] = (0, _react.useState)(false);
  var [initLoading, setInitLoading] = (0, _react.useState)(true);
  var [canRedo, setCanRedo] = (0, _react.useState)(false);
  var [canUndo, setCanUndo] = (0, _react.useState)(false);
  var [currentCell, setCurrentCell] = (0, _react.useState)();
  var [graphData, setGraphData] = (0, _react.useState)(_defaultData.default);
  var [assetsData, setAssetsData] = (0, _react.useState)(window._globalAssets);
  var [zoom, setZoom] = (0, _react.useState)(1); // 节点或线发生变化时调用

  var changeCells = (0, _ahooks.useMemoizedFn)(() => {
    if (graph && onChange) {
      onChange((0, _tools.getGraphJSONData)(graph));
    }
  });

  if (api && Reflect.has(api, 'current')) {
    api.current = {
      resize: () => {
        restoreData((0, _tools.getGraphJSONData)(graph), false);
        setLaneKey((0, _tools.getKey)());
      },
      getArchData: () => (0, _tools.getGraphJSONData)(graph)
    };
  } // 全屏显示


  var [isFullScreen, setIsFullScreen] = (0, _react.useState)(false); // 初始化数据
  // 从 indexdb 中恢复数据

  var restoreData = (0, _ahooks.useMemoizedFn)( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(function* (data, cache) {
      setInitLoading(true);
      var nodeDatas = data;

      if (cache) {
        yield _tools.dbHelper.ready();
        var store = yield _tools.dbHelper.findByPk('graphDatas', '1');
        var {
          id: storeId,
          updateTime,
          expired,
          data: storeData
        } = store || {};

        if (storeId && updateTime + expired > Date.now()) {
          if (storeData) nodeDatas = storeData;
        }
      }

      setGraphData((0, _tools.getGraphData)(nodeDatas, defaultEdgeShape));
      setInitLoading(false);
      yield (0, _tools.autoSaveJson)(null, graph, onAutoSave);
    });

    return function (_x, _x2) {
      return _ref2.apply(this, arguments);
    };
  }()); // 自动保存

  var autoSaveStop = (0, _ahooks.useInterval)( /*#__PURE__*/_asyncToGenerator(function* () {
    yield (0, _tools.autoSaveJson)(null, graph, onAutoSave);
  }), autoSaveInterval, {
    immediate: !!autoSaveInterval
  });
  (0, _react.useEffect)(() => {
    if (!autoSaveInterval) {
      autoSaveStop();
    }
  }, [autoSaveInterval]); // 合并资源

  (0, _react.useEffect)(() => {
    var globalAssets = _objectSpread(_objectSpread({}, assetsData), assets || {});

    window._globalAssets = globalAssets;
    setAssetsData(globalAssets);
  }, [assets]);
  (0, _ahooks.useDebounceEffect)(() => {
    restoreData(data, cache);
  }, [data, cache]); // 生成事件

  var {
    actionFunMap
  } = (0, _useHooks.default)({
    onRemoveLink,
    onRemoveNode,
    onAddLink,
    onSave,
    changeCells,
    defaultEdgeShape
  }); // 画布事件响应

  var handlerActions = (0, _ahooks.useMemoizedFn)(action => {
    actionFunMap[action] && actionFunMap[action](currentCell, graph, {
      setVisible,
      setCurrentCell,
      setZoom,
      zoom,
      fullContainer: archWrapper.current,
      setIsFullScreen
    });
  }); // 拖拽进入创建环节

  var dragToCreateNode = node => {
    setCurrentCell(node);
    (0, _tools.nextTick)(() => setVisible(true));
  }; // 创建新节点


  var addNewNode = (0, _ahooks.useMemoizedFn)(nodeData => {
    var lane = graph === null || graph === void 0 ? void 0 : graph.getCellById(nodeData.preId);
    var node = graph === null || graph === void 0 ? void 0 : graph.createNode((0, _tools.createGraphNodeData)(nodeData, {
      graph,
      assets: assetsData
    }));

    if (node && lane) {
      lane.addChild(node);
    }

    if (currentCell) {
      graph === null || graph === void 0 ? void 0 : graph.removeCell(currentCell);
      setCurrentCell(undefined);
    }

    changeCells();
  }); // 修改节点信息

  var updateNode = (0, _ahooks.useMemoizedFn)(node => {
    var nodeData = node.data || {};
    var {
      shape
    } = node;
    var grahpNode = graph === null || graph === void 0 ? void 0 : graph.getCellById(nodeData.id);
    grahpNode === null || grahpNode === void 0 ? void 0 : grahpNode.setData(_objectSpread({}, nodeData), {
      silent: true
    });
    grahpNode === null || grahpNode === void 0 ? void 0 : grahpNode.attr((0, _tools2.getNodeAttr)(shape, nodeData, assets));
    changeCells();
  }); // 创建或修改节点信息

  var submitNode = (0, _ahooks.useMemoizedFn)( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator(function* (node) {
      var flag = false;
      var nodeData = node.data || {};
      var isNew = !nodeData.id;
      var ret = undefined;

      if (isNew) {
        if (onCreateNode) {
          ret = yield onCreateNode(nodeData);
        } else {
          flag = true;
        }
      } else {
        if (onUpdateNode) {
          ret = yield onUpdateNode(nodeData);
        } else {
          flag = true;
        }
      }

      if (!flag && !!ret) {
        nodeData = ret;
        flag = true;
      } // 如果flag true 创建节点


      if (flag) {
        if (isNew) {
          addNewNode(nodeData);
        } else {
          updateNode(node);
        }
      }

      return flag;
    });

    return function (_x3) {
      return _ref4.apply(this, arguments);
    };
  }());
  (0, _ahooks.useMount)(() => {
    (0, _tools2.registerAll)(registerList);
    (0, _tools2.registerModuleNode)();
    (0, _tools2.registerEdge)();
    (0, _iconfont.default)();
  });
  (0, _ahooks.useUpdateEffect)(() => {
    if (visible) setCreateModalKey((0, _tools.getKey)());
  }, [visible]);
  return /*#__PURE__*/_react.default.createElement("div", {
    ref: archWrapper,
    className: "ra-arch-design"
  }, /*#__PURE__*/_react.default.createElement(_antd.Spin, {
    spinning: initLoading,
    tip: "\u6570\u636E\u521D\u59CB\u5316\u4E2D\uFF0C\u8BF7\u7A0D\u5019..."
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-aside"
  }, /*#__PURE__*/_react.default.createElement(_List.default, {
    onNodeCreate: dragToCreateNode,
    configs: moduleConfig,
    graph: graph,
    assets: assetsData,
    defaultNodeShape: defaultNodeShape,
    moduleNodeShape: moduleNodeShape
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-content"
  }, /*#__PURE__*/_react.default.createElement(_CreateNode.default, {
    key: createModalKey,
    visible: visible,
    onClose: () => setVisible(false),
    node: currentCell,
    onSubmit: submitNode,
    rootNode: drawerRootNode
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-actions"
  }, /*#__PURE__*/_react.default.createElement(_ActionButtons.default, {
    onActions: handlerActions,
    isFullScreen: isFullScreen,
    canRedo: canRedo,
    canUndo: canUndo,
    showActions: showActions,
    actions: actions,
    appendActions: appendActions
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "ra-arch-laneGroup"
  }, /*#__PURE__*/_react.default.createElement(_Lane.default, {
    key: laneKey,
    setCurrentCell: setCurrentCell,
    data: graphData,
    onActions: handlerActions,
    onLoad: setGraph,
    assets: assetsData,
    zoom: zoom,
    isFullScreen: isFullScreen,
    setCanRedo: setCanRedo,
    setCanUndo: setCanUndo,
    onUndoOrRedo: onUndoOrRedo,
    defaultEdgeShape: defaultEdgeShape
  })))));
});
var _default = ArchDesign;
exports.default = _default;